/**
 * Created by qiaozhi on 16/6/30.
 */
module.exports = function () {
  function copyArray(arr) {
    var listArr = []
    for (var i = 0, len = arr.length; i < len; i++) {
      listArr.push(arr[i]);
    }
    return listArr;
  }

  function bubbleSort(arr, direction, orderby, shouldCopy) {
    var len = arr.length,
        d = direction || "ascend", s;

    var listArr = [];
    if (shouldCopy) {
      listArr = copyArray(arr);
    }
    else {
      listArr = arr;
    }

    for (var i = 0; i < len - 1; i++) {
      for (var j = i + 1; j < len; j++) {
        var value1 = orderby ? listArr[i][orderby] : listArr[i];
        var value2 = orderby ? listArr[j][orderby] : listArr[j];
        var shouldExchange = false;
        var result = false;

        // number类型比较
        if (!isNaN(value1) && !isNaN(value2)) {
          if (value1 - value2 < 0) { result = "SMALLER"; } else { result = "BIGGER"; }
        }
        // string类型比较
        else {
          if (value1 < value2) { result = "SMALLER"; } else { result = "BIGGER"; }
        }

        if (d == "ascend" && result == "BIGGER") {
          shouldExchange = true;
        }
        else if (d != "ascend" && result == "SMALLER") {
          shouldExchange = true;
        }

        if (shouldExchange){
          s = listArr[j];
          listArr[j] = listArr[i];
          listArr[i] = s;
        }
      }
    }
    return listArr;
  }

  Array.prototype.sort = function (param) {
    var arr = this;
    var config = param || {};
    var direction = config.direction || "ascend";
    var orderby = config.orderby || null;
    var copy = config.copy;
    return bubbleSort(arr, direction, orderby, copy);
  }

  Array.prototype.each = function (cb) {
    var arr = this, len = this.length, stopFlag = {found: false};
    for (var i = 0; i < len; i++) {
      if (cb && !stopFlag.found) cb(arr[i], i, stopFlag);
    }
  }

  Array.prototype.find = function (v) {
    var arr = this, index = -1, value;
    var valueType = typeof (v);
    if (valueType != "object") {
      valueType = "BASIC";
    }
    else {
      for (var i in v) {
        valueType = i;
        break;
      }
    }
    arr.each(function(el, i, stopFlag){
      if ((valueType == "BASIC" && el == value) || (valueType != "BASIC" && v[valueType] == el[valueType])) {
        index = i;
        stopFlag.found = true;
      }
    });
    return index;
  }

  Array.prototype.clear = function () {
    this.length = 0;
  }

  Array.prototype.insert = function (index, value) {
    this.splice(index, 0, value);
  }

  Array.prototype.move = function (srcIndex, destIndex) {
    var value = this[srcIndex];
    this.remove(srcIndex);
    this.insert(destIndex, value);
  }

  Array.prototype.remove = function (index) {
    this.splice(index, 1);
  }

  Array.prototype.findRemove = function (value) {
    var index = this.indexOf(value);
    if (index >= 0) {
      this.remove(index);
    }
  }
}